﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using System.Xml;
using System.Reflection;
using System.ComponentModel;
using System.Collections.Generic;


namespace PUBCOM
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileObj
    {
        #region 构造函数


        private bool _alreadyDispose = false;
        public FileObj()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        ~FileObj()
        {
            Dispose();
        }

        protected virtual void Dispose(bool isDisposing)
        {
            if (_alreadyDispose) return;
            //if (isDisposing)
            //{
            //    if (xml != null)
            //    {
            //        xml = null;
            //    }
            //}
            _alreadyDispose = true;
        }
        #endregion

        #region IDisposable 成员

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        #region 取得文件后缀名






        /****************************************
         * 函数名称：GetPostfixStr
         * 功能说明：取得文件后缀名






         * 参    数：filename:文件名称
         * 调用示列：


         *           string filename = "aaa.aspx";        
         *           string s = Lib.FileObj.GetPostfixStr(filename);         
        *****************************************/
        /// <summary>
        /// 取后缀名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>.gif|.html格式</returns>
        public static string GetPostfixStr(string filename)
        {
            int start = filename.LastIndexOf(".");
            int length = filename.Length;
            string postfix = filename.Substring(start, length - start);
            return postfix;
        }

        /// <summary>
        /// 取后缀名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>.gif|.html格式</returns>
        public static string GetPostfixStr(string filename,string indexof)
        {
            int start = filename.LastIndexOf(indexof);
            int length = filename.Length;
            string postfix = filename.Substring(start, length - start);
            postfix = filename.Replace(postfix, "");
            return postfix;
        }
        #endregion

        #region 写文件






        /****************************************
         * 函数名称：WriteFile
         * 功能说明：当文件不存时，则创建文件，并追加文件


         * 参    数：Path:文件路径,Strings:文本内容
         * 调用示列：


         *           string Path = Server.MapPath("Default2.aspx");       
         *           string Strings = "这是我写的内容啊";
         *           Lib.FileObj.WriteFile(Path,Strings);
        *****************************************/
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteFile(string Path, string Strings)
        {
            string FolderPath = GetPostfixStr(Path, @"\");
            FolderCreate(FolderPath);
            if (!System.IO.File.Exists(Path))
            {
                //Directory.CreateDirectory(Path);
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.UTF8);
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();


        }
        #endregion

        #region 读文件






        /****************************************
         * 函数名称：ReadFile
         * 功能说明：读取文本内容


         * 参    数：Path:文件路径
         * 调用示列：


         *           string Path = Server.MapPath("Default2.aspx");       
         *           string s = Lib.FileObj.ReadFile(Path);
        *****************************************/
        /// <summary>
        /// 读文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <returns></returns>
        public static string ReadFile(string Path)
        {
            string s = "";
            if (!System.IO.File.Exists(Path))
                s = "不存在相应的目录";
            else
            {
                StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));
                s = f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }

            return s;
        }
        #endregion

        #region 追加文件
        /****************************************
         * 函数名称：FileAdd
         * 功能说明：追加文件内容


         * 参    数：Path:文件路径,strings:内容
         * 调用示列：


         *           string Path = Server.MapPath("Default2.aspx");     
         *           string Strings = "新追加内容";
         *           Lib.FileObj.FileAdd(Path, Strings);
        *****************************************/
        /// <summary>
        /// 追加文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="strings">内容</param>
        public static void FileAdd(string Path, string strings)
        {
            StreamWriter sw = File.AppendText(Path);
            sw.Write(strings);
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
        #endregion

        #region 拷贝文件
        /****************************************
         * 函数名称：FileCoppy
         * 功能说明：拷贝文件


         * 参    数：OrignFile:原始文件,NewFile:新文件路径


         * 调用示列：


         *           string OrignFile = Server.MapPath("Default2.aspx");     
         *           string NewFile = Server.MapPath("Default3.aspx");
         *           EC.FileObj.FileCoppy(OrignFile, NewFile);
        *****************************************/
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="OrignFile">原始文件</param>
        /// <param name="NewFile">新文件路径</param>
        public static void FileCoppy(string OrignFile, string NewFile)
        {
            File.Copy(OrignFile, NewFile, true);
        }

        #endregion

        #region 删除文件
        /****************************************
         * 函数名称：FileDel
         * 功能说明：删除文件


         * 参    数：Path:文件路径
         * 调用示列：


         *           string Path = Server.MapPath("Default3.aspx");    
         *           EC.FileObj.FileDel(Path);
        *****************************************/
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="Path">路径</param>
        public static void FileDel(string Path)
        {
            File.Delete(Path);
        }
        #endregion

        #region 移动文件
        /****************************************
         * 函数名称：FileMove
         * 功能说明：移动文件


         * 参    数：OrignFile:原始路径,NewFile:新文件路径


         * 调用示列：


         *            string OrignFile = Server.MapPath("../说明.txt");    
         *            string NewFile = Server.MapPath("http://www.cnblogs.com/说明.txt");
         *            Lib.FileObj.FileMove(OrignFile, NewFile);
        *****************************************/
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="OrignFile">原始路径</param>
        /// <param name="NewFile">新路径</param>
        public static void FileMove(string OrignFile, string NewFile)
        {
            File.Move(OrignFile, NewFile);
        }
        #endregion

        #region 在当前目录下创建目录
        /****************************************
         * 函数名称：FolderCreate
         * 功能说明：在当前目录下创建目录


         * 参    数：OrignFolder:当前目录,NewFloder:新目录


         * 调用示列：


         *           string OrignFolder = Server.MapPath("test/");    
         *           string NewFloder = "new";
         *           Lib.FileObj.FolderCreate(OrignFolder, NewFloder); 
        *****************************************/
        /// <summary>
        /// 在当前目录下创建目录
        /// </summary>
        /// <param name="OrignFolder">当前目录</param>
        /// <param name="NewFloder">新目录</param>
        public static void FolderCreate(string OrignFolder, string NewFloder)
        {
            Directory.SetCurrentDirectory(OrignFolder);
            Directory.CreateDirectory(NewFloder);
        }
        /****************************************
         * 函数名称：FolderCreate
         * 功能说明：在当前目录下创建目录


         * 参    数：OrignFolder:当前目录,NewFloder:新目录


         * 调用示列：


         *           string OrignFolder = Server.MapPath("test/");    
         *           
         *           Lib.FileObj.FolderCreate(OrignFolder); 
        *****************************************/
        /// <summary>
        /// 创建目录如果目录不存在则创建，
        /// </summary>
        /// <param name="OrignFolder">当前目录</param>
        public static void FolderCreate(string OrignFolder)
        {
            switch (Directory.Exists(OrignFolder))
            {
                case false:
                    Directory.CreateDirectory(OrignFolder); 
                    break;
                default:
                break;
            }
            
        }
        #endregion

        #region 把一条Model记录序列化xml
        /****************************************
         * 函数名称：ModelToXML
         * 功能说明：把一条数据对象转成xml的格式输出


         * 参    数：model数据对象(可以是一条记录)
         * 输    出：xml格式的字符串
         * 调用示列：


         *           object model = table.tables[0];
         *           Lib.FileObj.ModelToXML(model);
        *****************************************/
        /// <summary>
        /// 把一条Model记录序列化xml
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string ModelToXML(object model,string rootName)
        {
            string text = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<root><" + rootName + ">";
            if (model != null)
            {
                foreach (PropertyInfo info in model.GetType().GetProperties())
                {
                    if (info.GetValue(model, null) != null)
                    {
                        text += "<" + info.Name + "><![CDATA[" + info.GetValue(model, null).ToString() + "]]></" + info.Name + ">\n";
                    }
                    else
                    {
                        text += "<" + info.Name + "><![CDATA[[Null]]]></" + info.Name + ">\n";
                    }
                }
            }
            text += "</" + rootName + ">\n</root>\n";
            return text;
        }

        /****************************************
         * 函数名称：ModelToXML
         * 功能说明：把一条数据对象转成xml的格式输出
         * 参    数：model数据对象(可以是一条记录)
         * 输    出：xml格式的字符串
         * 调用示列：
         *           object model = table.tables[0];
         *           Lib.FileObj.ModelToXML(model);
        *****************************************/
        /// <summary>
        /// 把一条记录保存成xml的格式
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string ModelToXML(object model)
        {
            return ModelToXML(model, "Model");
        }

        
        /// <summary>
        /// 把xml序列化成Model
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="SampleModel"></param>
        /// <returns></returns>
        public static object XMLToModel(string xml, object SampleModel)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(xml);
            DataTable dt = ds.Tables[0];
            //return dt;
            int i = 0;
            foreach (PropertyInfo info in SampleModel.GetType().GetProperties())
            {
                string name = dt.Columns[i].ColumnName;
                object value = dt.Rows[0][i];
                if (name == info.Name)
                {
                    if (value.ToString() != "[Null]")
                    {
                        if (info.PropertyType == typeof(Guid))
                        {
                            info.SetValue(SampleModel, new Guid(value.ToString()), null);
                        }
                        else
                        {
                            info.SetValue(SampleModel, ChangeType(value, info.PropertyType), null);
                        }
                    }
                    else
                    {
                        info.SetValue(SampleModel, null, null);
                    }
                }
                i++;
            }
            return SampleModel;
        }
        /// <summary>
        /// 数据类型转换
        /// </summary>
        /// <param name="value">要转换的数据</param>
        /// <param name="conversionType">转换的类型</param>
        /// <returns></returns>
        public static object ChangeType(object value, Type conversionType)
        {
            // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
            // checking properties on conversionType below.
            if (conversionType == null)
            {
                throw new ArgumentNullException("conversionType");
            } // end if

            // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

            if (conversionType.IsGenericType &&
              conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
                // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx),
                // determine what the underlying type is
                // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
                // have a type--so just return null
                // Note: We only do this check if we're converting to a nullable type, since doing it outside
                // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
                // value is null and conversionType is a value type.
                if (value == null)
                {
                    return null;
                } // end if

                // It's a nullable type, and not null, so that means it can be converted to its underlying type,
                // so overwrite the passed-in conversion type with this underlying type
                NullableConverter nullableConverter = new NullableConverter(conversionType);

                conversionType = nullableConverter.UnderlyingType;
            } // end if

            // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
            // nullable type), pass the call on to Convert.ChangeType
            return Convert.ChangeType(value, conversionType);
        }
        #endregion

        #region 
        /// <summary>
        /// 得到审核状态描述，没找到的话返回 ""
        /// </summary>
        /// <param name="ID">状态编号</param>
        /// <param name="XmlPath">xml文件路径</param>
        /// <param name="flName">状态描述的字段名</param>
        /// <returns></returns>
        public static string State(string ID, string XmlPath, string flName)
        {
            string strType = "";
            DataSet ds = new DataSet();
            ds.ReadXml(XmlPath);
            if (ds != null)
            {
                DataView dv = ds.Tables[0].DefaultView;
                for (int i = 0; i < dv.Count; i++)
                {
                    if (ID == dv[i].Row[0].ToString())
                    {
                        strType = dv[i].Row[flName].ToString();
                        break;
                    }
                }
            }
            return strType;

        }

        /// <summary>
        /// 得到审核状态描述，没找到的话返回 ""
        /// </summary>
        /// <param name="ID">状态编号</param>
        /// <returns></returns>
        public static string AuditState(string ID)
        {
            return State(ID, HttpContext.Current.Server.MapPath("~/XML/AuditState.xml"), "desc");
        }

        #endregion

        //#region 文件上传 
        //public Model.FileUpLoadModel UpLoadFile(HtmlInputFile InputFile, string filePath, string myfileName, bool isRandom)
        //{
        //    Model.FileUpLoadModel fp = new Model.FileUpLoadModel();
        //    string fileName, fileExtension;
        //    string saveName;
        //    //建立上传对象　 
        //    HttpPostedFile postedFile = InputFile.PostedFile;
        //    fileName = System.IO.Path.GetFileName(postedFile.FileName);
        //    fileExtension = System.IO.Path.GetExtension(fileName);
        //    ////根据类型确定文件格式　 
        //    //AppConfig app = new AppConfig();
        //    //string format = app.GetPath("FileUpLoad/Format");
        //    ////如果格式都不符合则返回　 
        //    //if (format.IndexOf(fileExtension) == -1)
        //    //{
        //    //    throw new ApplicationException("上传数据格式不合法");
        //    //}
        //    //　 
        //    //根据日期和随机数生成随机的文件名　 
        //    //　 
        //    if (myfileName != string.Empty)
        //    {
        //        fileName = myfileName;
        //    }
        //    if (isRandom)
        //    {
        //        Random objRand = new Random();
        //        System.DateTime date = DateTime.Now;
        //        //生成随机文件名　 
        //        saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99) * 97 + 100);
        //        fileName = saveName + fileExtension;
        //    }
        //    string phyPath = HttpContext.Current.Request.MapPath(filePath);
        //    //判断路径是否存在,若不存在则创建路径　 
        //    DirectoryInfo upDir = new DirectoryInfo(phyPath);
        //    if (!upDir.Exists)
        //    {
        //        upDir.Create();
        //    }
        //    //保存文件　 
        //    try
        //    {
        //        postedFile.SaveAs(phyPath + fileName);
        //        fp.FilePath = filePath + fileName;
        //        fp.FileExtension = fileExtension;
        //        fp.FileName = fileName;
        //    }
        //    catch
        //    {
        //        throw new ApplicationException("上传失败!");
        //    }
        //    //返回上传文件的信息　 
        //    return fp;
        //}
        
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="current"></param>
        ///// <param name="myFileName"></param>
        ///// <returns></returns>
        //public static List<Model.FileUpLoadModel> UpLoadFile(Page current, string myFileName)
        //{
        //    List<Model.FileUpLoadModel> filenamelist = new List<Model.FileUpLoadModel>();
        //    for (int i = 0; i < current.Request.Files.Count; i++)
        //    {
        //        Model.FileUpLoadModel model = UpLoadFile(current.Request.Files[i], Lib.Parameters.DocumentPath, myFileName);
        //        if (model != null)
        //        {
        //            filenamelist.Add(model);
        //        }
        //    }
        //    return filenamelist;
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="FileUpload1"></param>
        ///// <param name="myFileName"></param>
        ///// <returns></returns>
        //public static Model.FileUpLoadModel UpLoadFile(FileUpload FileUpload1, string myFileName)
        //{
        //    return UpLoadFile(FileUpload1.PostedFile, Lib.Parameters.DocumentPath, myFileName);
        //}


        //public static Model.FileUpLoadModel UpLoadFile(HttpPostedFile postedFile, string savePath, string myFileName)
        //{
        //    Model.FileUpLoadModel fp = new Model.FileUpLoadModel();
        //    string fileName, fileExtension;
        //    string saveName;
        //    int FileSize = 0;
        //    //建立上传对象　 
        //    if (postedFile.FileName.Length == 0)
        //    {
        //        return null;
        //    }
        //    fileName = System.IO.Path.GetFileName(postedFile.FileName);
        //    fileExtension = System.IO.Path.GetExtension(fileName);
        //    FileSize = postedFile.ContentLength;
        //    if (myFileName != string.Empty)
        //    {
        //        fileName = myFileName;
        //    }
        //    saveName = Guid.NewGuid().ToString().Replace("-", "");// date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99) * 97 + 100);
        //    //fileName = saveName + fileExtension;
        //    saveName += fileExtension;
        //    DateTime date = DateTime.Now;
        //    string filepath = savePath + date.Year + "/" + date.Month.ToString() + "/" + date.Day.ToString();//文件路径
        //    string phyPath = HttpContext.Current.Request.MapPath(filepath);
        //    //判断路径是否存在,若不存在则创建路径　 
        //    DirectoryInfo upDir = new DirectoryInfo(phyPath);
        //    if (!upDir.Exists)
        //    {
        //        upDir.Create();
        //    }
        //    //保存文件　 
        //    try
        //    {
        //        postedFile.SaveAs(phyPath + "/" + saveName);
        //        fp.FilePath = filepath + saveName;
        //        fp.FileExtension = fileExtension;
        //        fp.FileName = fileName;
        //        fp.ContentLength = FileSize;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new ApplicationException("上传失败!");
        //    }
        //    //返回上传文件的信息　 
        //    return fp;
        //}

        //#endregion

        #region 下载文件的几种方法TODO:TING







        //TransmitFile实现下载
        /// <summary>
        /// TransmitFile实现下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransmitFileDownFile(string strFileName)
        {
            HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            string filename = System.IO.Path.GetFileName(strFileName);

            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpContext.Current.Server.UrlPathEncode(filename));

            //Server.UrlPathEncode()解决文件名的乱码问题.

            HttpContext.Current.Response.TransmitFile(strFileName);
        }    //WriteFile实现下载
        /// <summary>
        /// WriteFile实现下载
        /// </summary>
        /// <param name="clientName"></param>
        /// <param name="filePath"></param>
        public void WriteFileDownFile(string clientName, string filePath)
        {
            string clex = System.IO.Path.GetExtension(clientName);
            string filex = System.IO.Path.GetExtension(filePath);
            if (clex.Length == 0)
            {
                clientName = clientName + filex;
            }
            else
            {
                if (clex != filex)
                {
                    try
                    {
                        string s = clientName.Substring(0, clientName.Length - clex.Length);
                        clientName = s + filex;
                    }
                    catch { }
                }
            }
            FileInfo fileInfo = new FileInfo(filePath);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + clientName);
            HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            HttpContext.Current.Response.WriteFile(fileInfo.FullName);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        //WriteFile分块下载
        /// <summary>
        /// WriteFile分块下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void WriteFileDownFileSpan(string clientfileName, string filePath)
        {
            if (!System.IO.File.Exists(filePath))
            {
                HttpContext.Current.Response.Write("<script>alert('找不到该文件');window.close();</script>");
            }
            string clex = System.IO.Path.GetExtension(clientfileName.Trim());
            string filex = System.IO.Path.GetExtension(filePath);
            string strEXT = filex;
            if (clex.Trim().Length == 0)
            {
                clientfileName = clientfileName + filex;
            }
            else
            {
                if (clex.ToUpper() != filex.ToUpper())
                {
                    try
                    {
                        string s = clientfileName.Substring(0, clientfileName.Length - clex.Length);
                        clientfileName = s + filex;
                    }
                    catch { }
                }
            }


            clientfileName = clientfileName.Trim();

            for (int i = 0; i < System.IO.Path.GetInvalidPathChars().Length; i++)
            {
                clientfileName = clientfileName.Trim().Replace(System.IO.Path.GetInvalidPathChars()[i].ToString(), string.Empty);
            }

            clientfileName = clientfileName.Replace(System.IO.Path.PathSeparator.ToString(), string.Empty);

            int maxLength = 155;
            string strEXTc = strEXT.ToUpper().Replace(".", "");
            if (strEXTc == "XLS" || strEXTc == "XLSX")
            {
                maxLength = 100;
            }


            int length = HttpUtility.UrlEncode(clientfileName).Length;
            while (length > maxLength)
            {
                int index = clientfileName.LastIndexOf(".");
                if (index > 0)
                {
                    clientfileName = clientfileName.Substring(0, index - 1) + clientfileName.Substring(index);
                }
                else
                {
                    clientfileName = clientfileName.Substring(0, clientfileName.Length - 1);
                }
                length = HttpUtility.UrlEncode(clientfileName).Length;
            }



            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

            if (fileInfo.Exists == true)
            {
                const long ChunkSize = 102400;//100K 每次读取文件，只读取100Ｋ，这样可以缓解服务器的压力
                byte[] buffer = new byte[ChunkSize];

                HttpContext.Current.Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//获取下载的文件总大小



                if (dataLengthToRead == 0)
                {
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.End();
                    HttpContext.Current.Response.Close();
                    FileStreamDownFile(clientfileName, filePath);
                    return;
                }

                string cname = HttpUtility.UrlEncode(clientfileName, System.Text.Encoding.UTF8);

                strEXT = strEXT.ToUpper().Replace(".", "");
                if (strEXT == "DOC" || strEXT == "RTF" || strEXT == "DOCX")
                {
                    HttpContext.Current.Response.ContentType = "application/msword";
                }
                else if (strEXT == "XLS" || strEXT == "XLSX")
                {
                    HttpContext.Current.Response.ContentType = "application/x-msexcel";
                }
                else if (strEXT == "GIF")
                    HttpContext.Current.Response.ContentType = "image/gif";
                else if (strEXT == "JPG")
                    HttpContext.Current.Response.ContentType = "image/jpeg";
                else if (strEXT == "BMP")
                    HttpContext.Current.Response.ContentType = "image/bmp";
                else if (strEXT == "PDF")
                    HttpContext.Current.Response.ContentType = "application/pdf";
                else if (strEXT == "PPT")
                    HttpContext.Current.Response.ContentType = "application/vnd.ms-powerpoint";
                else if (strEXT == "TIF" || strEXT == "TIFF")
                    HttpContext.Current.Response.ContentType = "image/tiff";
                else if (strEXT == "TXT")
                    HttpContext.Current.Response.ContentType = "text/plain";
                else if (strEXT == "WPS")
                    HttpContext.Current.Response.ContentType = "application/vnd.ms-works";
                else if (strEXT == "ZIP")
                    HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
                else
                {
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                }


                //HttpContext.Current.Response.ContentType = "application/octet-stream";
                if (PUBCOM.WebUtil.GetQueryString("open") != "1")
                {
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + cname.Replace("+", "%20"));
                    //HttpContext.Current.Response.AddHeader("Content-Disposition", " filename=" + cname.Replace("+", "%20"));
                }
                else
                {
                    HttpContext.Current.Response.AddHeader("Content-Disposition", " filename=" + cname.Replace("+", "%20"));
                }
                while (dataLengthToRead > 0 && HttpContext.Current.Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小



                    HttpContext.Current.Response.OutputStream.Write(buffer, 0, lengthRead);
                    HttpContext.Current.Response.Flush();
                    
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                iStream.Close();
                HttpContext.Current.Response.Close();
            }
        }


        //WriteFile分块下载
        /// <summary>
        /// WriteFile分块下载在浏览器里打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void WriteFileDownFileSpanOpen(Page p, string clientfileName, string filePath)
        {
            if (!System.IO.File.Exists(filePath))
            {
                //HttpContext.Current.Response.Write("<script>alert('找不到该文件');history.go(-1);</script>");
                p.ClientScript.RegisterStartupScript(this.GetType(), "start", "alert('找不到该文件');window.opener=null;window.open('','_self');window.close();", true);
            }
            string clex = System.IO.Path.GetExtension(clientfileName.Trim());
            string filex = System.IO.Path.GetExtension(filePath);
            string strEXT = filex;
            if (clex.Trim().Length == 0)
            {
                clientfileName = clientfileName + filex;
            }
            else
            {
                if (clex.ToUpper() != filex.ToUpper())
                {
                    try
                    {
                        string s = clientfileName.Substring(0, clientfileName.Length - clex.Length);
                        clientfileName = s + filex;
                    }
                    catch { }
                }
            }


            clientfileName = clientfileName.Trim();

            for (int i = 0; i < System.IO.Path.GetInvalidPathChars().Length; i++)
            {
                clientfileName = clientfileName.Trim().Replace(System.IO.Path.GetInvalidPathChars()[i].ToString(), string.Empty);
            }

            clientfileName = clientfileName.Replace(System.IO.Path.PathSeparator.ToString(), string.Empty);

            int maxLength = 155;
            string strEXTc = strEXT.ToUpper().Replace(".", "");
            if (strEXTc == "XLS" || strEXTc == "XLSX")
            {
                maxLength = 100;
            }


            int length = HttpUtility.UrlEncode(clientfileName).Length;
            while (length > maxLength)
            {
                int index = clientfileName.LastIndexOf(".");
                if (index > 0)
                {
                    clientfileName = clientfileName.Substring(0, index - 1) + clientfileName.Substring(index);
                }
                else
                {
                    clientfileName = clientfileName.Substring(0, clientfileName.Length - 1);
                }
                length = HttpUtility.UrlEncode(clientfileName).Length;
            }



            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

            if (fileInfo.Exists == true)
            {
                const long ChunkSize = 102400;//100K 每次读取文件，只读取100Ｋ，这样可以缓解服务器的压力
                byte[] buffer = new byte[ChunkSize];

                HttpContext.Current.Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//获取下载的文件总大小




                if (dataLengthToRead == 0)
                {
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.End();
                    HttpContext.Current.Response.Close();
                    FileStreamDownFile(clientfileName, filePath);
                    return;
                }

                string cname = HttpUtility.UrlEncode(clientfileName, System.Text.Encoding.UTF8);

                strEXT = strEXT.ToUpper().Replace(".", "");
                if (strEXT == "DOC" || strEXT == "RTF" || strEXT == "DOCX")
                {
                    HttpContext.Current.Response.ContentType = "application/msword";
                }
                else if (strEXT == "XLS" || strEXT == "XLSX")
                {
                    HttpContext.Current.Response.ContentType = "application/x-msexcel";
                }
                else if (strEXT == "GIF")
                    HttpContext.Current.Response.ContentType = "image/gif";
                else if (strEXT == "JPG")
                    HttpContext.Current.Response.ContentType = "image/jpeg";
                else if (strEXT == "BMP")
                    HttpContext.Current.Response.ContentType = "image/bmp";
                else if (strEXT == "PDF")
                    HttpContext.Current.Response.ContentType = "application/pdf";
                else if (strEXT == "PPT")
                    HttpContext.Current.Response.ContentType = "application/vnd.ms-powerpoint";
                else if (strEXT == "TIF" || strEXT == "TIFF")
                    HttpContext.Current.Response.ContentType = "image/tiff";
                else if (strEXT == "TXT")
                    HttpContext.Current.Response.ContentType = "text/plain";
                else if (strEXT == "WPS")
                    HttpContext.Current.Response.ContentType = "application/vnd.ms-works";
                else if (strEXT == "ZIP")
                    HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
                else
                {
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                }



                //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + cname.Replace("+", "%20"));
                HttpContext.Current.Response.AddHeader("Content-Disposition", " filename=" + cname.Replace("+", "%20"));

                while (dataLengthToRead > 0 && HttpContext.Current.Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小




                    HttpContext.Current.Response.OutputStream.Write(buffer, 0, lengthRead);
                    HttpContext.Current.Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                HttpContext.Current.Response.Close();
            }
        }


        //WriteFile分块下载
        /// <summary>
        /// WriteFile分块下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void WriteFileDownFileSpan(string clientfileName, byte[] buffer)
        {

            clientfileName = clientfileName.Trim();
            string strEXTc = System.IO.Path.GetExtension(clientfileName);
            for (int i = 0; i < System.IO.Path.GetInvalidPathChars().Length; i++)
            {
                clientfileName = clientfileName.Trim().Replace(System.IO.Path.GetInvalidPathChars()[i].ToString(), string.Empty);
            }

            clientfileName = clientfileName.Replace(System.IO.Path.PathSeparator.ToString(), string.Empty);

            int maxLength = 155;

            if (strEXTc == "XLS" || strEXTc == "XLSX")
            {
                maxLength = 100;
            }


            int length = HttpUtility.UrlEncode(clientfileName).Length;
            while (length > maxLength)
            {
                int index = clientfileName.LastIndexOf(".");
                if (index > 0)
                {
                    clientfileName = clientfileName.Substring(0, index - 1) + clientfileName.Substring(index);
                }
                else
                {
                    clientfileName = clientfileName.Substring(0, clientfileName.Length - 1);
                }
                length = HttpUtility.UrlEncode(clientfileName).Length;
            }

            byte[] bytes = buffer;

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.ContentType = "application/octet-stream";

            HttpContext.Current.Response.AddHeader("Content-Disposition", "  filename=" + HttpUtility.UrlEncode(clientfileName).Replace("+", "%20"));

            // HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(clientfileName).Replace("+", "%20")); //通知浏览器下载文件而不是打开
            HttpContext.Current.Response.BinaryWrite(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 流方式下载

        /// </summary>
        /// <param name="clientfileName"></param>
        /// <param name="filePath"></param>
        public void FileStreamDownFile(string clientfileName, string filePath)
        {
            string clex = System.IO.Path.GetExtension(clientfileName);
            string filex = System.IO.Path.GetExtension(filePath);
            if (clex.Length == 0)
            {
                clientfileName = clientfileName + filex;
            }
            else
            {
                if (clex != filex)
                {
                    try
                    {
                        string s = clientfileName.Substring(0, clientfileName.Length - clex.Length);
                        clientfileName = s + filex;
                    }
                    catch { }
                }
            }

            //以字符流的形式下载文件

            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(clientfileName, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.BinaryWrite(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();

        }



        #endregion
    }
}
